var app = getApp()

Page({
  data: {
    loaded: false,
    orderId: '',
    orderSource: '',
    commented: false,
    userName: '',
    userPortrait: '',
    rateLevel: null,
    redBagMoney: 0,
    rates: [0, 0, 0, 0, 0],
    commentedTags: [],
    products: [],
    billboard: []
  },
  onLoad: function (options) {
    if (!options.orderId) {
      return app.toast.error('参数错误：缺少订单ID')
    }
    if (!options.userId) {
      return app.toast.error('参数错误：缺少用户ID')
    }
    if (!options.orderSource) {
      return app.toast.error('参数错误：缺少订单来源')
    }
    this.setData({
      orderId: options.orderId,
      userId: options.userId,
      orderSource: options.orderSource || 'online'
    })
    app.showLoading()
    app.ready(() => {
      this.getCommentInfo()
      this.getBillBoard()
    })
  },
  getCommentInfo: function () {
    let params = {
      userId: this.data.userId,
      orderId: this.data.orderId,
      orderSource: this.data.orderSource
    }
    params = {
      __zaofans: true,
      datas: JSON.stringify(params)
    }
    app.request('/yuanmai_we/comments/get/info', params).then(res => {
      this.setData({
        commented: res.commented,
        userPortrait: res.userPortrait,
        userName: res.userName,
        redBagMoney: res.commentReward.amount,
        rates: this.reduceRates(+res.comment.grade - 1),
        rateLevel: +res.comment.grade,
        commentedTags: res.comment.tag.split('，'),
        comment: res.comment.content,
        rewards: res.rewards,
        products: (res.dtls || []).map(item => ({content: '', grade: 0, ...item})),
        loaded: true
      })
    }, err => {
      app.toast.error(err)
    }).finally(app.hideLoading)
  },
  getBillBoard: function () {
    app.get('/yuanmai_we/mealList/mostPopular/get').then(res => {
      this.setData({
        billboard: res
      })
    })
  },
  reduceRates: function (index) {
    let rates = this.data.rates.map((item, i) => {
      if (i <= index) {
        return 1
      } else {
        return 0
      }
    })

    return rates
  },
  doleRedBag: function () {
    wx.navigateTo({
      url: `/pages/my/receiveRedbag/receiveRedbag?orderId=${this.data.orderId}&userId=${app.globalData.userid}&orderSource=${this.data.orderSource}`
    })
  }
})
